<?php

require_once 'Form.php';
require_once 'ConfigPhp.php';
require_once 'ConfigFormBuilder.php';
require_once 'RequestHandler.php';
class ConfigEditorHandler extends RequestHandler
{
	var $cfg=NULL;
	var $source = NULL;
	var $params = NULL;

	public function handle ()
	{
		$form = $this->getForm();
		disp_form($form);
	} // end of method d
	public function handle_POST ()
	{
		$form = $this->getForm();
		$form->process();
		if ($form->status === 'ok') {
			//request_redirect($_SERVER['REQUEST_URI']);
			request_redirect('?m=about');
		} else {
			disp_form($form);
		}
	} // end of method do_POST

	public function getConfig ()
	{
		if (!isset($this->cfg)) {
			$this->cfg = new ConfigPhp(array('source'=>$this->source));
		}
		return $this->cfg;
	} // end of method getConfig
	public function getForm ()
	{
		if (!isset($this->form)) {
			$cfg = $this->getConfig();
			$this->form = $this->buildForm($cfg);
		}
		return $this->form;
	} // end of method getForm
	public function buildForm ($cfg)
	{
		$builder = new ConfigFormBuilder(array('params' => $this->params));
		$form = $builder->build($cfg);
		$form[   'action'] = $_SERVER['REQUEST_URI'];
		$form[    'event'] = 'edit';
		$form['validator'] = array($this, 'validate');
		$form[    'saver'] = array($this, 'formSave');

		foreach ($form['fields'] as $fn =>& $fc) {
			if (method_exists($this, 'validate_'.$fn)) {
				$fc['validator'] = array($this, 'validate_'.$fn);
			}
			if (method_exists($this, 'default_'.$fn)) {
				$fc['default'] = array($this, 'default_'.$fn);
			}
		}

		error_reporting(E_ALL);
		ini_set('display_errors', 1);

		$f = new Form($form);
		return $f;
	} // end of method buildForm
	public function validate ($f)
	{
	} // end of method validator
	public function formSave ($form)
	{
		$env = $form->vhash;
		return $this->save($env);
	} // end of method save
	public function save ($env)
	{
		$cfg = $this->getConfig();
		foreach ($env as $k=>$v) {
			$cfg->setParam($k, $v);
		}
	} // end of method save
}
